﻿using AntMovement.Core;
using AntMovement.Core.Attributes;
using AntMovement.Core.Entity;
using AntMovement.Core.Hardware;
using AntMovement.Core.IParameter;
using AntMovement.Core.Logic;
using AntMovement.Core.Logic.Base;
using AntMovement.Core.Model;
using AntMovement.Parameter;
using System;
using System.Linq;

namespace AntMovement.Handle.BluingFilm
{
    //[FlowAttributes(nameof(ModuleMotion), 2)]
    public class ModuleMotion1 : TaskBase
    {
        #region 轴变量
        private IAxis _axitX;
        private IAxis _axitY;
        private IAxis _axitZ;
        private IAxis _axitR;
        private AxisStatus _axisStatusY;
        private AxisStatus _axisStatusZ;
        private AxisStatus _axisStatusR;
        private AxisStatus _axisStatusX;
        #endregion
        #region 上升沿
        private bool _xUpRisingEdge = false, _xDownRisingEdge = false, _yUpRisingEdge = false, _yDownRisingEdge = false, _zUpRisingEdge = false,
            _zDownRisingEdge = false, _rUpRisingEdge = false, _rDownRisingEdge = false, _homeRisingEdge = false;
        private bool _homeXYR = false, _homeZ = false, _startHome = false;
        private bool _homeAlarm = false, _alarmPosition = false, _moveOKNGNegation = false;
        #endregion
        #region 定时器
        private Ton _tonHome = new Ton();
        private Ton _tonDW = new Ton();
        private Ton _tonCalibration = new Ton();
        #endregion
        #region 点位
        private PointPositionInfoModel 拍照位;
        private PointPositionInfoModel 取料位1;
        private PointPositionInfoModel 取料位2;
        private PointPositionInfoModel 贴料位;
        #endregion
        #region 输入点
        private NormalOpen _机械手吸盘信号;
        private NormalOpen _撕膜无料检测光纤;
        private NormalOpen _物料吸盘检测光纤;
        private NormalOpen _物料到位光纤;
        private NormalClose _急停;
        private NormalOpen _停止;
        #endregion
        #region 输出点
        private ICoil _移动物料吸盘真空阀;
        private ICoil _底座物料吸盘真空阀;
        #endregion
        #region 报警变量
        private bool _物料检测失败 = false;
        private bool _出料口有料 = false;
        private bool _CalibrationAlarm = false;
        #endregion
        #region 私有变量
        public long _CachesCoordinate { get; set; }
        public int _stepVI { get; set; }
        #endregion
        public ModuleMotion1(ITemporaryParameter temporary, IIOParameter iop, IAxisParameter axisp, IDialogHost dialogHost, ILog log)
            : base(temporary, iop, axisp, dialogHost, log)
        {
            _急停 = iop.GetNormalClose("急停");
            _移动物料吸盘真空阀 = iop.GetCoil("移动物料吸盘真空阀");
            _底座物料吸盘真空阀 = iop.GetCoil("底座物料吸盘真空阀");
            _撕膜无料检测光纤 = iop.GetNormalOpen("撕膜无料检测光纤");
            _物料吸盘检测光纤 = iop.GetNormalOpen("物料吸盘检测光纤");
            _物料到位光纤 = iop.GetNormalOpen("物料到位光纤");
            _机械手吸盘信号 = iop.GetNormalOpen("机械手吸盘信号");
            _停止 = iop.GetNormalOpen("停止");
            _axitX = axisp.GetAxis("X轴");
            _axitY = axisp.GetAxis("Y轴");
            _axitZ = axisp.GetAxis("Z轴");
            _axitR = axisp.GetAxis("R轴");
            _axisStatusX = _axitX.GetAxisStatus();
            _axisStatusY = _axitY.GetAxisStatus();
            _axisStatusZ = _axitZ.GetAxisStatus();
            _axisStatusR = _axitR.GetAxisStatus();
            
            拍照位 = ((Parameter.AxisParameter)axisp).PointPosition.FirstOrDefault(x => x.Name == "避让位");
            取料位1 = ((Parameter.AxisParameter)axisp).PointPosition.FirstOrDefault(x => x.Name == "取料位1");
            取料位2 = ((Parameter.AxisParameter)axisp).PointPosition.FirstOrDefault(x => x.Name == "取料位2");
            贴料位 = ((Parameter.AxisParameter)axisp).PointPosition.FirstOrDefault(x => x.Name == "贴料位");
            _axisStatusZ.HEND = false;
            _temporary.HomeComplete = false;
        }

        public override void Resetting()
        {
            _homeXYR = false;
            _homeZ = false;
            _startHome = false;
            _alarmPosition = false;
            _homeAlarm = false;
            _物料检测失败 = false;
            _step = 0;
            _CalibrationAlarm = false;
        }

        public override void Handle()
        {
            _temporary.SystemStatus.AlarmStop = _homeAlarm || _alarmPosition || _物料检测失败 || _CalibrationAlarm;
            if (_temporary.SystemStatus.Auto)
            {
                if (!_homeRisingEdge && !_temporary.HomeComplete)
                {
                    _dialogHost.DialogShow("轴未全部回原，请先回原在开机！！！", Core.Enum.LogLevel.Error, hostDialog: Core.Enum.PopUpType.Global);
                    _homeAlarm = true;
                }
                if (!_homeRisingEdge && _temporary.HomeComplete)
                {
                    _homeRisingEdge = true;
                }
                if (!_homeAlarm)
                {
                    if (_step == 0)
                    {
                        //switch (_temporary.Number)
                        //{
                        //    case 1:
                        //        NextStep();
                        //        break;
                        //    case 2:
                        //        NextStep(20);
                        //        break;
                        //}
                    }
                    if (_step == 10)
                    {
                        //位置1
                        //检测轴位置停止并检测是否允许取料
                        if (!_axisStatusY.SportStatus)
                        {
                            PointPositionMove(取料位1);
                        }
                        if (Math.Abs(_axisStatusY.CurrentPostion - 取料位1.YPulse) <= 20 && !_axisStatusY.SportStatus)
                        {
                            _CachesCoordinate = _axisStatusZ.CurrentPostion;
                            NextStep(20);
                        }
                    }
                    if (_step == 20)
                    {
                        //位置2
                        if (!_axisStatusY.SportStatus)
                        {
                            PointPositionMove(取料位2);
                        }
                        if (Math.Abs(_axisStatusY.CurrentPostion - 取料位2.YPulse) <= 20 && !_axisStatusY.SportStatus)
                        {
                            _CachesCoordinate = _axisStatusZ.CurrentPostion;
                            NextStep();
                        }
                    }
                    if (_step == 30)
                    {
                        //Z轴下降
                        if (!_axisStatusZ.SportStatus)
                        {
                            _axitZ.SetProfile();
                            _axitZ.Move(取料位2.ZPulse, 1, 2);
                        }
                        if ((Math.Abs(_axisStatusZ.CurrentPostion - 取料位2.ZPulse) <= 20) && !_axisStatusZ.SportStatus)
                        {
                            _CachesCoordinate = _axisStatusX.CurrentPostion;
                            NextStep();
                        }
                    }
                    if (_step == 40)
                    {
                        _移动物料吸盘真空阀.Execute(true);
                        NextStep();
                    }
                    if (_step == 50)
                    {
                        //Z轴上升
                        if (!_axisStatusZ.SportStatus)
                        {
                            _axitZ.SetProfile();
                            _axitZ.Move(0, 1, 2);
                        }
                        if ((Math.Abs(_axisStatusZ.CurrentPostion - 0) <= 20) && !_axisStatusZ.SportStatus)
                        {
                            _CachesCoordinate = _axisStatusX.CurrentPostion;
                            NextStep();
                        }
                    }
                    if (_step == 60)
                    {
                        if (!_axisStatusY.SportStatus)
                        {
                            PointPositionMove(贴料位);
                        }
                        if (Math.Abs(_axisStatusY.CurrentPostion - 贴料位.YPulse) <= 20 && !_axisStatusY.SportStatus)
                        {
                            _CachesCoordinate = _axisStatusZ.CurrentPostion;
                            NextStep();
                        }
                    }
                    if (_step == 70)
                    {
                        //Z轴下降
                        if (!_axisStatusZ.SportStatus)
                        {
                            _axitZ.SetProfile();
                            _axitZ.Move(取料位2.ZPulse, 1, 2);
                        }
                        if ((Math.Abs(_axisStatusZ.CurrentPostion - 取料位2.ZPulse) <= 20) && !_axisStatusZ.SportStatus)
                        {
                            _CachesCoordinate = _axisStatusX.CurrentPostion;
                            NextStep();
                        }
                    }
                    if (_step == 80)
                    {
                        _移动物料吸盘真空阀.Execute(false);
                        NextStep();
                    }
                    if (_step == 90)
                    {
                        //Z轴上升
                        if (!_axisStatusZ.SportStatus)
                        {
                            _axitZ.SetProfile();
                            _axitZ.Move(0, 1, 2);
                        }
                        if ((Math.Abs(_axisStatusZ.CurrentPostion - 0) <= 20) && !_axisStatusZ.SportStatus)
                        {
                            _CachesCoordinate = _axisStatusX.CurrentPostion;
                            NextStep();
                        }
                    }
                    if (_step == 100)
                    {
                        _step = 0;
                        //if (_位移负压信号.Execute())
                        //{
                        //    _temporary.Status_模组运动.Permit_TakeMaterials = false;
                        //    if (!_axisStatusX.SportStatus && !_moveOKNGNegation)
                        //    {
                        //        bool bl = (new Random().Next() % 2) == 0;
                        //        if (bl)
                        //        {
                        //            //PointPositionMove(OK流拉);
                        //        }
                        //        else
                        //        {
                        //            //PointPositionMove(NG流拉);
                        //        }
                        //        _moveOKNGNegation = true;
                        //    }
                        //    else if (Math.Abs(_CachesCoordinate - _axisStatusX.CurrentPostion) >= 100)
                        //    {
                        //        _moveOKNGNegation = false;
                        //        NextStep();
                        //    }
                        //}
                        //else
                        //{
                        //    _物料检测失败 = true;
                        //    _dialogHost.DialogShow("位移负压信号检测异常!!!", Core.Enum.LogLevel.Error, hostDialog: Core.Enum.PopUpType.Global);
                        //}
                    }
                }
            }
            if (_temporary.SystemStatus.ManualOperation)
            {
                #region 标定
                if (!_homeAlarm)
                {
                    if (_stepVI == 0)
                    {
                        if (_temporary.Calibration)
                        {
                            if (!_homeRisingEdge && (!_axisStatusR.ORG || !_axisStatusX.ORG || !_axisStatusY.ORG || !_axisStatusZ.HEND))
                            {
                                _dialogHost.DialogShow("轴未全部回原，请先回原在进行标定！！！", Core.Enum.LogLevel.Error, hostDialog: Core.Enum.PopUpType.Global);
                                _homeAlarm = true;
                            }
                            else
                            {
                                _stepVI = 10;
                                _temporary.Calibration = false;
                            }
                        }
                    }
                    if (_stepVI == 10)
                    {
                        _temporary.VisualInteraction.Machine.X = _axisStatusX.CurrentPostion;
                        _temporary.VisualInteraction.Machine.Y = _axisStatusY.CurrentPostion;
                        _temporary.VisualInteraction.Machine.Z = _axisStatusZ.CurrentPostion;
                        _temporary.VisualInteraction.Machine.R = _axisStatusR.CurrentPostion;
                        _temporary.VisualInteraction.Cmd.Calibration = 1;
                        _stepVI = 20;
                    }
                    if (_stepVI == 20)
                    {
                        if (_temporary.VisualInteraction.Cmd.Calibration == 2)
                        {
                            _tonCalibration.Time(2000, false);
                            _stepVI = 30;
                        }
                        else
                        {
                            _tonCalibration.Time(2000, true);
                            if (_tonCalibration.Out)
                            {
                                _dialogHost.DialogShow("等待视觉完成信号超时！！！", Core.Enum.LogLevel.Error, hostDialog: Core.Enum.PopUpType.Global);
                                _CalibrationAlarm = true;
                            }
                        }
                    }
                    if (_stepVI == 30)
                    {

                    }
                }
                #endregion
            }
        }

        private void PointPositionMove(PointPositionInfoModel point)
        {
            if (!_axisStatusX.SportStatus)
            {
                _axitX.SetProfile();
                _axitX.Move(point.XPulse, 1, 2);
            }
            if (!_axisStatusY.SportStatus)
            {
                _axitY.SetProfile();
                _axitY.Move(point.YPulse, 1, 2);
            }
            if (!_axisStatusR.SportStatus)
            {
                _axitR.SetProfile();
                _axitR.Move(point.RPulse, 1, 2);
            }
        }

        public override void SafeStop()
        {
            _axitX.Stop(1);
            _axitY.Stop(1);
            _axitZ.Stop(1);
            _axitR.Stop(1);
        }

        public override void EmergencyStop()
        {
            _axitX.Stop(1);
            _axitY.Stop(1);
            _axitZ.Stop(1);
            _axitR.Stop(1);
            _temporary.HomeComplete = false;
        }
    }
}
